package com.wxsoft.java.demo05.jackson;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class MemberJSON {

    public static void main(String[] args) throws Exception {
        String strURL = "http://gateway-sit.baozun.com/openapi/member/account/big/data/msg/query";
        System.out.println((new MemberJSON()).getURLContent(strURL));
    }

    private static String getURLContent(String strURL) throws Exception {
        URL url = new URL(strURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        // 发送POST请求必须设置如下两行
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);

        //设置提交方式
        httpConn.setRequestMethod("POST");
        //设置请求头
        httpConn.setRequestProperty("Content-Type", "application/json");
        httpConn.setRequestProperty("client-id", "DEV201805001");
        httpConn.setRequestProperty("client-secret", "PLmpfFsKv6mF6G3QVR9izWk82nxmelEm");

        String parameter = "{ \"tenantCode\":\"880001\",\"startTime\":\"20180815000000\", \"endTime\":\"20180820000000\"}";
        PrintWriter writer = new PrintWriter(httpConn.getOutputStream());
        writer.write(parameter);
        writer.flush();
        writer.close();

        httpConn.connect();

        BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
        String line;
        StringBuffer buffer = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();

        httpConn.disconnect();
        System.out.println(buffer.toString());

        String jsonStr  = reader.toString();
        JSONObject jsonObj = new JSONObject(jsonStr);
        JSONObject refObj = new JSONObject(jsonObj.getString("refObj"));
        String existType = refObj.getString("existType");
        //把json格式转换成对象
        JacksonParse jacksonParse = (JacksonParse) JacksonParse.jsonToObject(existType, MemberEntity.class);
        System.out.println(jacksonParse);
        return buffer.toString();
    }

}

